/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.utils;

import net.dgg.dggcloud.core.cache.CacheManager;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.constant.CommonConstant;
import net.dgg.dggcloud.service.jrcrm.entity.customer.*;
import net.dgg.dggcloud.service.jrcrm.vo.CusAttrVo;
import org.apache.poi.ss.formula.functions.T;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: TranslateMapUtil
 * @Description: 翻译数据字典
 * @Author 汤宏
 * @date 2017/11/7 17:24
 */

public class TranslateMapUtil {
    /**
     * 集合数据中字典翻译
     *
     * @param column     需要翻译的列的key 如：String[] column = {"businessstatus","typecode"};
     * @param columnList 需要翻译的列
     */
    public static List<Map> translateMap(String[] column, List<Map> columnList) {
        if (null != column && null != columnList) {
            for (int i = 0; i < columnList.size(); i++) {
                Map<String, Object> map = columnList.get(i);
                for (String key : map.keySet()) {
                    if (useLoop(column, key)) {
                        if (null != map.get(key)) {
                            String val = translateCodes(map.get(key).toString());
                            map.put(key, val);
                        }
                    }
                }
            }
        }
        return columnList;
    }

    /**
     * 翻译列表中的组织机构
     *
     * @param column     需要翻译的列的key 如：String[] column = {"orgid"};
     * @param columnList 需要翻译的列
     */
    public static List<Map> translateOrgMap(String[] column, List<Map> columnList) {
        if (null != column && null != columnList) {
            for (int i = 0; i < columnList.size(); i++) {
                Map<String, Object> map = columnList.get(i);
                for (String key : map.keySet()) {
                    if (useLoop(column, key)) {
                        if (null != map.get(key)) {
                            String val = TranslateMapUtil.translateOrgName(Long.valueOf(map.get(key).toString()));
                            map.put(key, val);
                        }
                    }
                }
            }
        }
        return columnList;
    }

    /**
     * 集合数据中某个code对应的颜色，返回的map中会放上key+Color的颜色类型，如businessstatusColor
     *
     * @param column     需要翻译的列的key 如：String[] column = {"businessstatus","typecode"};
     * @param columnList 需要翻译的列
     */
    public static List<Map> translateColorMap(String[] column, List<Map> columnList) {
        if (null != column && null != columnList) {
            try {
                for (int i = 0; i < columnList.size(); i++) {
                    Map<String, Object> map = columnList.get(i);
                    Map<String, Object> newColorMap = new HashMap();
                    for (String key : map.keySet()) {
                        if (useLoop(column, key)) {
                            if (null != map.get(key)) {
                                newColorMap.put(key + "Color", StatusColorUtil.getColor(String.valueOf(map.get(key))));
                            }
                        }
                    }
                    map.putAll(newColorMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return columnList;
    }

    /**
     * 针对对象进行属性code翻译
     *
     * @param column 要翻译的属性数组（String）;如：String[] column = {"businessstatus","typecode"};
     * @param o      要翻译的对象
     * @return
     * @throws IllegalAccessException
     * @Author 周潮
     */
    public static Object translateObject(String[] column, Object o) throws IllegalAccessException {
        if (null != column && null != o) {
            Field[] fs = o.getClass().getDeclaredFields();
            for (int i = 0; i < fs.length; i++) {
                Field f = fs[i];
                f.setAccessible(true); //设置些属性是可以访问的
                Object val = f.get(o);//得到此属性的值
                for (String col : column) {
                    if (col.equals(f.getName())) {//如果传入的列名跟属性名相同，则翻译
                        String type = f.getType().toString();//得到此属性的类型
                        if (type.endsWith("String")) {
                            f.set(o, (null == val ? null : translateCodes(val.toString())));        //给属性设值
                        } else {
                            throw new BizException("翻译对象属性code失败，属性类型错误！", 10005);
                        }
                    }
                }
            }
        }
        return o;
    }

    /**
     * 根据单个字典CODE获取数据字典值
     *
     * @param code 字典CODE
     * @return
     */
    public static String translateCode(String code) {
        String value = "";
        if (!StringUtils.isEmpty(code)) {
            value = (String) CacheManager.getOperator().get(CommonConstant.TREEBOOK_KEY + code.trim());
        }
        return StringUtils.isNotEmpty(value) ? value : code;
    }

    /**
     * 根据部门id获取部门名称
     *
     * @param orgId 部门id
     * @return
     */
    public static String translateOrgName(Long orgId) {
        String value = "";
        if (null != orgId) {
            value = String.valueOf(CacheManager.getOperator().get(CommonConstant.ORGANIZATION_KEY + orgId.toString()));
        }
        return StringUtils.isNotEmpty(value) ? value : String.valueOf(orgId);
    }

    /**
     * 根据多个字典CODE获取数据字典值，逗号分割：CODE1,CODE2
     *
     * @param codes 字典CODE  逗号分割：CODE1,CODE2
     * @return
     */
    public static String translateCodes(String codes) {
        String values = codes;
        if (!StringUtils.isEmpty(codes)) {
            String[] codeStr = codes.split(",");
            values = "";
            for (int i = 0; i < codeStr.length; i++) {
                String val = TranslateMapUtil.translateCode(codeStr[i]);
                values += (i == 0 ? val : "，" + val);
            }

        }
        return values;
    }

    /**
     * 查询数组中有无某个值
     *
     * @param arr
     * @param targetValue
     * @return
     */
    public static boolean useLoop(String[] arr, String targetValue) {
        for (String s : arr) {
            if (s.equals(targetValue))
                return true;
        }
        return false;
    }

    /**
     * 翻译客户属性-只用于客户列表查询<br/>
     *
     * @param mapList <br/>
     *                customerattrflag：客户属性key<br/>
     * @return
     * @Author: 周潮
     */
    public static List<Map> translateCusAttr(List<Map> mapList) {
        //翻译客户属性（逗号分隔code）
        for (Map map : mapList) {
            if (null != map.get("customerattrflag")) {
                String[] cusAttrArr = map.get("customerattrflag").toString().split(",");
                StringBuffer afterTranslate = new StringBuffer();//接收翻译后的客户属性
                for (String str : cusAttrArr) {
                    afterTranslate.append(TranslateMapUtil.translateCode(str) + ",");
                }
                map.put("customerattrflag", afterTranslate.substring(0, afterTranslate.length() - 1));
            }
        }
        return mapList;
    }

    /**
     * 翻译商机的显示状态
     *
     * @param listMap
     * @return
     */
    public static List<Map> translateBusinessShowStatusMap(List<Map> listMap) {
        if (null != listMap && !listMap.isEmpty()) {
            for (Map map : listMap) {
                String status = null == map.get("businessstatus") ? "" : String.valueOf(map.get("businessstatus"));
                String location = null == map.get("businesslocation") ? "" : String.valueOf(map.get("businesslocation"));
                String oprate = null == map.get("businessoperate") ? "" : String.valueOf(map.get("businessoperate"));
                map.put("businessShowStatus", BusinessStatusUtil.translateShowStatus(status, location,oprate));
            }
        }
        return listMap;

    }

    /**
     * 翻译客户属性
     * @param cusAttrVo 客户属性vo，包含八个客户属性
     * @return
     * @throws IllegalAccessException
     */
    public static CusAttrVo translateAttr(CusAttrVo cusAttrVo) throws IllegalAccessException {

        if(null != cusAttrVo){
            //房屋字段翻译
            if(null != cusAttrVo.getAttrBuildings() && cusAttrVo.getAttrBuildings().size() > 0){
                String[] attrBuildingsColumn = {"buildingType", "buildingPosition", "buildingArea", "certificate", "mortgageBank", "mortgageWay", "repaymentWay"};//需要翻译的列， List<Map>中Map的key
                List<AttrBuilding> attrBuildingList = new ArrayList<>();
                for (AttrBuilding attrBuilding: cusAttrVo.getAttrBuildings()) {
                    attrBuildingList.add((AttrBuilding) TranslateMapUtil.translateObject(attrBuildingsColumn, attrBuilding));
                }
                cusAttrVo.setAttrBuildings(attrBuildingList);
            }

            //车辆字段翻译
            if(null != cusAttrVo.getAttrVehicles() && cusAttrVo.getAttrVehicles().size() > 0) {
                String[] attrVehiclesColumn = {"vehicleBrand", "vehicleType", "mortgageWay", "vehicleInsurance", "insuranceCompany"};//需要翻译的列， List<Map>中Map的key
                List<AttrVehicle> attrVehicleList = new ArrayList<>();
                for (AttrVehicle attrVehicle : cusAttrVo.getAttrVehicles()) {
                    attrVehicleList.add((AttrVehicle) TranslateMapUtil.translateObject(attrVehiclesColumn, attrVehicle));
                }
                cusAttrVo.setAttrVehicles(attrVehicleList);
            }

            //保单字段翻译
            if(null != cusAttrVo.getAttrPolicy()) {
                String[] attrPolicyColumn = {"insuranceCompany", "paymentWay", "paymentYears", "policyHolder"};//需要翻译的列， List<Map>中Map的key
                cusAttrVo.setAttrPolicy((AttrPolicy) TranslateMapUtil.translateObject(attrPolicyColumn, cusAttrVo.getAttrPolicy()));
            }

            //工作字段翻译
            if(null != cusAttrVo.getAttrJob()) {
                String[] attrJobColumn = {"jobNature", "managementIndustry", "enterpriseNature", "wagesPayForm"};//需要翻译的列， List<Map>中Map的key
                cusAttrVo.setAttrJob((AttrJob) TranslateMapUtil.translateObject(attrJobColumn, cusAttrVo.getAttrJob()));
            }

            //社保字段翻译
            if(null != cusAttrVo.getAttrSocialSecurity()) {
                String[] attrSocialSecurityColumn = {"purchaser"};//需要翻译的列， List<Map>中Map的key
                cusAttrVo.setAttrSocialSecurity((AttrSocialSecurity) TranslateMapUtil.translateObject(attrSocialSecurityColumn, cusAttrVo.getAttrSocialSecurity()));
            }

            //公积金字段翻译
            if(null != cusAttrVo.getAttrAccFund()) {
                String[] attrAccFundColumn = {"purchaseUnit"};//需要翻译的列， List<Map>中Map的key
                cusAttrVo.setAttrAccFund((AttrAccFund) TranslateMapUtil.translateObject(attrAccFundColumn, cusAttrVo.getAttrAccFund()));
            }

            //负债字段翻译
            if(null != cusAttrVo.getAttrLiability()) {
                String[] attrLiabilityColumn = {"liabilityType", "isOverdue"};//需要翻译的列， List<Map>中Map的key
                cusAttrVo.setAttrLiability((AttrLiability) TranslateMapUtil.translateObject(attrLiabilityColumn, cusAttrVo.getAttrLiability()));
            }

            //其他字段翻译
            if(null != cusAttrVo.getAttrOther()) {
                String[] attrOtherColumn = {"other"};//需要翻译的列， List<Map>中Map的key
                cusAttrVo.setAttrOther((AttrOther) TranslateMapUtil.translateObject(attrOtherColumn, cusAttrVo.getAttrOther()));
            }
        }
        return cusAttrVo;
    }

    public  static List<Map> translateOrigincode(List<Map> list,List<Map> typeList ) {
        boolean flag = false;
        for (Map b : list) {
            flag = false;
            for (Map s : typeList) {
                if (null != b.get("origincode")) {
                    if (b.get("origincode").toString().equals(s.get("code").toString())) {
                        if (null != s.get("type")) {
                            if (1 == Integer.parseInt(s.get("type").toString())) {//表单
                                b.put("origincodetype", "表单");
                            } else if (2 == Integer.parseInt(s.get("type").toString())) {//非表单
                                b.put("origincodetype", "非表单");
                            } else if (0 == Integer.parseInt(s.get("type").toString())) {//其它
                                b.put("origincodetype", s.get("name"));
                            }
                        }else{
                            b.put("origincodetype", s.get("name"));
                        }
                        flag = true;
                        break;
                    }
                }
            }
            if(!flag){
                b.put("origincodetype", b.get("origincode"));
            }
        }
        return list;
    }
}
